import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';

class InfiniteListViewPage extends StatelessWidget {
  const InfiniteListViewPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('无限列表'),
      ),
      body: const InfiniteListView(),
    );
  }
}

class InfiniteListView extends StatefulWidget {
  const InfiniteListView({super.key});

  @override
  State<StatefulWidget> createState() {
    return _InfiniteListViewState();
  }
}

class _InfiniteListViewState extends State<InfiniteListView> {
  /// 表尾标记
  static const loadingTag = '##loading##';
  final _words = <String>[loadingTag];

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemBuilder: (context, index) {
        /// 如果到了表尾
        if (_words[index] == loadingTag) {
          if (_words.length - 1 < 100) {
            /// 如果列表数少于100，则继续获取数据
            _retrieveData();

            /// 加载提示
            return Container(
                padding: const EdgeInsets.all(16.0),
                alignment: Alignment.center,
                child: const SizedBox(
                  width: 24.0,
                  height: 24.0,
                  child: CircularProgressIndicator(strokeWidth: 2.0),
                ));
          } else {
            return Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.all(16.0),
              child: const Text(
                "没有更多了",
                style: TextStyle(color: Colors.grey),
              ),
            );
          }
        }
        // 显示单词列表
        return ListTile(
          title: Text("$index ${_words[index]}"),
        );
      },
      separatorBuilder: (context, index) => const Divider(
        height: .0,
      ),
      itemCount: _words.length,
    );
  }

  void _retrieveData() {
    Future.delayed(const Duration(seconds: 2)).then((e) {
      setState(() {
        /// 重新构建列表
        _words.insertAll(
          _words.length - 1,

          /// 每次生成20个单词
          generateWordPairs().take(20).map((e) => e.asPascalCase).toList(),
        );
      });
    });
  }
}
